package main

import (
	"ScreenRead/logic"
	"context"
	"embed"
	"fmt"
	"github.com/go-vgo/robotgo"
	hook "github.com/robotn/gohook"
	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// TODO 收藏队列
// TODO 集成识图
// TODO 集成翻译
// TODO 隐藏任务栏，半透明

//go:embed all:frontend/dist
var assets embed.FS

var app = NewApp()

func main() {
	// 异步监听
	go bindKey()

	// 启动应用
	if err := wails.Run(&options.App{
		Title:  "ScreenRead",
		Width:  1024,
		Height: 512,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
		OnStartup:        app.startup,
		OnBeforeClose:    func(ctx context.Context) (prevent bool) { return false },
		Bind: []interface{}{
			app,
		},
	}); err != nil {
		println("Error:", err.Error())
	}
}

// 绑定截图按键 TODO 自定义按键
func bindKey() {
	events := robotgo.EventStart()
	alt, q := false, false

	for {
		if !alt || !q {
			for event := range events {
				if event.Keycode == hook.Keycode["alt"] {
					if event.Kind == hook.KeyHold || event.Kind == hook.KeyDown {
						alt = true
					} else {
						alt = false
					}
				} else if event.Keycode == hook.Keycode["q"] {
					if event.Kind == hook.KeyHold || event.Kind == hook.KeyDown {
						q = true
					} else {
						q = false
					}
				}
				if alt && q {
					goto EXEC
				}
			}
		}

	EXEC:
		x0, y0, x1, y1 := 0, 0, 0, 0
		for event := range events {
			if event.Button == 3 && event.Kind == hook.MouseHold {
				x0, y0 = robotgo.GetMousePos()
				fmt.Println(x0, y0)
				continue
			}
			if event.Button == 3 && (event.Kind == hook.MouseDown || event.Kind == hook.MouseUp) {
				x1, y1 = robotgo.GetMousePos()
				fmt.Println(x1, y1)
				break
			}
		}
		fmt.Println("截图结束")

		// 反向框选支持
		if x1-x0 < 0 {
			x0, x1 = x1, x0
		}
		if y1-y0 < 0 {
			y0, y1 = y1, y0
		}
		alt, q = false, false

		base64Img := logic.ScreenShot(x0, y0, x1-x0, y1-y0)
		if x1-x0 == 0 || y1-y0 == 0 {
			runtime.EventsEmit(app.ctx, "ShotComplete", base64Img, [2][]string{make([]string, 0), make([]string, 0)})
		} else {
			runtime.EventsEmit(app.ctx, "ShotComplete", base64Img, logic.ScreenRead(base64Img))
		}
	}
}
